<template>
  <Layout :user="user" :on-logout="handleLogout">
    <div class="dashboard-container bg-light-bg-primary dark:bg-dark-bg-primary blue:bg-blue-bg-primary min-h-screen transition-colors duration-300">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay" v-loading="true">
      <div class="loading-content">
        <div class="loading-text">加载中...</div>
      </div>
    </div>
    
    <div class="dashboard-header">
      <h2 class="text-2xl font-bold text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary mb-2">仪表盘</h2>
      <p class="text-light-text-secondary dark:text-dark-text-secondary blue:text-blue-text-secondary">欢迎回来，{{ userName }}</p>
    </div>
    
    <!-- 统计卡片区域 -->
    <div class="stats-cards">
      <el-card class="stat-card bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary border border-light-border dark:border-dark-border blue:border-blue-border">
        <div class="stat-content">
          <div class="stat-icon bg-light-bg-accent dark:bg-dark-bg-accent blue:bg-blue-bg-accent">
            <el-icon><User class="text-accent-color" /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value text-2xl font-bold text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary">{{ totalVisitors }}</div>
            <div class="stat-label text-light-text-secondary dark:text-dark-text-secondary blue:text-blue-text-secondary">今日访客</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary border border-light-border dark:border-dark-border blue:border-blue-border">
        <div class="stat-content">
          <div class="stat-icon bg-light-bg-accent dark:bg-dark-bg-accent blue:bg-blue-bg-accent">
            <el-icon><Calendar class="text-accent-color" /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value text-2xl font-bold text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary">{{ todayTasks }}</div>
            <div class="stat-label text-light-text-secondary dark:text-dark-text-secondary blue:text-blue-text-secondary">今日任务</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary border border-light-border dark:border-dark-border blue:border-blue-border">
        <div class="stat-content">
          <div class="stat-icon bg-light-bg-accent dark:bg-dark-bg-accent blue:bg-blue-bg-accent">
            <el-icon><Check class="text-accent-color" /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value text-2xl font-bold text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary">{{ completedTasks }}</div>
            <div class="stat-label text-light-text-secondary dark:text-dark-text-secondary blue:text-blue-text-secondary">已完成任务</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary border border-light-border dark:border-dark-border blue:border-blue-border">
        <div class="stat-content">
          <div class="stat-icon bg-light-bg-accent dark:bg-dark-bg-accent blue:bg-blue-bg-accent">
            <el-icon><Warning class="text-accent-color" /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value text-2xl font-bold text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary">{{ pendingTasks }}</div>
            <div class="stat-label text-light-text-secondary dark:text-dark-text-secondary blue:text-blue-text-secondary">待处理任务</div>
          </div>
        </div>
      </el-card>
      
      <el-card class="stat-card bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary border border-light-border dark:border-dark-border blue:border-blue-border" @click="goToQRCodeVerification">
        <div class="stat-content">
          <div class="stat-icon bg-success-light dark:bg-success-dark blue:bg-success-blue text-success-color">
            <el-icon><Camera /></el-icon>
          </div>
          <div class="stat-info">
            <div class="stat-value text-2xl font-bold text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary">扫码</div>
            <div class="stat-label text-light-text-secondary dark:text-dark-text-secondary blue:text-blue-text-secondary">二维码验证</div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 图表区域 -->
    <div class="charts-container">
      <el-card class="chart-card bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary border border-light-border dark:border-dark-border blue:border-blue-border">
        <template #header>
          <div class="card-header">
            <span class="text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary">访客统计 (近7天)</span>
          </div>
        </template>
        <div class="chart-content">
          <div id="visitorsChart" style="width: 100%; height: 300px;"></div>
        </div>
      </el-card>
      
      <el-card class="chart-card bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary border border-light-border dark:border-dark-border blue:border-blue-border">
        <template #header>
          <div class="card-header">
            <span class="text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary">任务完成率</span>
          </div>
        </template>
        <div class="chart-content">
          <div id="taskCompletionChart" style="width: 100%; height: 300px;"></div>
        </div>
      </el-card>
    </div>
    
    <!-- 最近任务列表 -->
    <div class="recent-tasks">
      <el-card class="bg-light-bg-secondary dark:bg-dark-bg-secondary blue:bg-blue-bg-secondary border border-light-border dark:border-dark-border blue:border-blue-border">
        <template #header>
          <div class="card-header">
            <span class="text-light-text-primary dark:text-dark-text-primary blue:text-blue-text-primary">最近任务</span>
          </div>
        </template>
        <el-table :data="recentTasks" style="width: 100%">
          <el-table-column prop="id" label="任务ID" width="80" />
          <el-table-column prop="title" label="任务名称" />
          <el-table-column prop="status" label="状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" width="180" />
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-button type="primary" size="small" @click="viewTask(scope.row.id)" class="bg-accent-color hover:bg-accent-color/90">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>
      </div>
    </Layout>
  </template>

<script setup lang="ts">
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { useAuthStore } from '../../stores/auth'
import { useRouter } from 'vue-router'
import Layout from '../../components/common/Layout.vue'
import { User, Calendar, Check, Warning, Camera } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import request from '../../utils/request'
import { useThemeStore } from '../../stores/theme'

// 初始化主题
const themeStore = useThemeStore()
themeStore.initTheme()

// 使用auth store
const authStore = useAuthStore()
const router = useRouter()

// 用户名
const userName = computed(() => authStore.userInfo?.name || '未知用户')

// Layout组件需要的user props
const user = computed(() => ({
  name: authStore.userInfo?.name || '未知用户',
  role: authStore.userInfo?.role || 'guard',
  phone: authStore.userInfo?.phone || undefined,
  district: undefined // 根据实际情况设置
}))

// Layout组件需要的onLogout回调
const handleLogout = () => {
  authStore.logout()
  router.push('/login')
}

// 统计数据
const totalVisitors = ref(0)
const todayTasks = ref(0)
const completedTasks = ref(0)
const pendingTasks = ref(0)
const visitorsData = ref<{date: string, count: number}[]>([])
const taskCompletionData = ref<{name: string, value: number}[]>([])

// 最近任务数据
const recentTasks = ref<{id: string, title: string, status: string, createTime: string}[]>([])

// 加载状态
const loading = ref(true)

// 图表实例
let visitorsChart: any = null
let taskCompletionChart: any = null

// 获取状态标签类型
const getStatusTagType = (status: string): string => {
  const statusMap: Record<string, string> = {
    'completed': 'success',
    'pending': 'warning',
    'failed': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'completed': '已完成',
    'pending': '待处理',
    'failed': '已失败'
  }
  return statusMap[status] || status
}

// 获取图表颜色配置
const getChartColors = () => {
  const themeName = themeStore.currentTheme
  
  // 根据主题返回不同的颜色配置
  const colorConfigs = {
    light: {
      primary: '#1890ff',
      secondary: '#52c41a',
      warning: '#faad14',
      danger: '#f5222d',
      background: '#ffffff',
      text: '#333333',
      textSecondary: '#666666',
      border: '#e8e8e8'
    },
    dark: {
      primary: '#177ddc',
      secondary: '#4cae14',
      warning: '#d99e14',
      danger: '#d11f1f',
      background: '#1f1f1f',
      text: '#ffffff',
      textSecondary: '#cccccc',
      border: '#444444'
    },
    blue: {
      primary: '#1a90ff',
      secondary: '#67c23a',
      warning: '#e6a23c',
      danger: '#f56c6c',
      background: '#1e293b',
      text: '#ffffff',
      textSecondary: '#cbd5e1',
      border: '#475569'
    }
  }
  return colorConfigs[themeName] || colorConfigs.light
}

// 查看任务详情
const viewTask = (taskId: string) => {
  // 这里可以跳转到任务详情页面或显示任务详情弹窗
  console.log('查看任务:', taskId)
}

// 跳转到二维码验证页面
const goToQRCodeVerification = () => {
  router.push({ name: 'qrcode-verification' })
}

// 初始化访客统计图表
const initVisitorsChart = () => {
  const chartDom = document.getElementById('visitorsChart')
  if (!chartDom) return
  
  visitorsChart = echarts.init(chartDom)
  
  const colors = getChartColors()
  
  const option = {
    color: [colors.primary],
    tooltip: {
      trigger: 'axis',
      backgroundColor: colors.background,
      borderColor: colors.border,
      textStyle: {
        color: colors.text
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: visitorsData.value.map(item => item.date),
      axisLine: {
        lineStyle: {
          color: colors.border
        }
      },
      axisLabel: {
        color: colors.textSecondary
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: colors.border
        }
      },
      axisLabel: {
        color: colors.textSecondary
      },
      splitLine: {
        lineStyle: {
          color: colors.border,
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '访客数',
        type: 'line',
        stack: 'Total',
        data: visitorsData.value.map(item => item.count),
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: `${colors.primary}40`
            },
            {
              offset: 1,
              color: `${colors.primary}10`
            }
          ])
        },
        emphasis: {
          focus: 'series'
        }
      }
    ]
  }
  
  visitorsChart.setOption(option)
}

// 初始化任务完成率图表
const initTaskCompletionChart = () => {
  const chartDom = document.getElementById('taskCompletionChart')
  if (!chartDom) return
  
  taskCompletionChart = echarts.init(chartDom)
  
  const colors = getChartColors()
  
  // 根据数据为每个部分设置颜色
  const pieColors = taskCompletionData.value.map((_, index) => {
    const colorOptions = [colors.primary, colors.warning, colors.danger, colors.secondary]
    return colorOptions[index % colorOptions.length]
  })
  
  const option = {
    color: pieColors,
    tooltip: {
      trigger: 'item',
      backgroundColor: colors.background,
      borderColor: colors.border,
      textStyle: {
        color: colors.text
      }
    },
    legend: {
      top: '5%',
      left: 'center',
      textStyle: {
        color: colors.text
      }
    },
    series: [
      {
        name: '任务完成情况',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: colors.background,
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center',
          color: colors.text
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '20',
            fontWeight: 'bold',
            color: colors.text
          }
        },
        labelLine: {
          show: false
        },
        data: taskCompletionData.value
      }
    ]
  }
  
  taskCompletionChart.setOption(option)
}

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    loading.value = true
    
    // 获取统计数据
    const statsData = await request.get('/api/dashboard/stats')
    totalVisitors.value = statsData.totalVisitors || 0
    todayTasks.value = statsData.todayTasks || 0
    completedTasks.value = statsData.completedTasks || 0
    pendingTasks.value = statsData.pendingTasks || 0
    
    // 获取最近任务数据
    const tasksData = await request.get('/api/dashboard/tasks/recent')
    recentTasks.value = tasksData || []
    
    // 获取访客统计图表数据
    const visitorsDataValue = await request.get('/api/dashboard/visitors/stats/weekly')
    visitorsData.value = visitorsDataValue || []
    
    // 获取任务完成率数据
    const completionData = await request.get('/api/dashboard/tasks/completion')
    taskCompletionData.value = completionData || []
    
    // 初始化图表
    initVisitorsChart()
    initTaskCompletionChart()
  } catch (error) {
    console.error('获取仪表盘数据失败:', error)
    // 提供备用数据，避免页面空白
    provideBackupData()
  } finally {
    loading.value = false
  }
}

// 提供备用数据，避免页面空白
const provideBackupData = () => {
  // 使用与后端测试数据相似的备用数据
  totalVisitors.value = 50
  todayTasks.value = 20
  completedTasks.value = 15
  pendingTasks.value = 5
  
  // 备用的任务数据
  recentTasks.value = [
    { id: 'T001', title: '访客登记检查', status: 'completed', createTime: new Date().toLocaleString() },
    { id: 'T002', title: '安全巡逻', status: 'completed', createTime: new Date(Date.now() - 3600000).toLocaleString() },
    { id: 'T003', title: '设备巡检', status: 'pending', createTime: new Date(Date.now() - 7200000).toLocaleString() }
  ]
  
  // 备用的访客统计数据
  visitorsData.value = [
    { date: new Date(Date.now() - 6*86400000).toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'}), count: 30 },
    { date: new Date(Date.now() - 5*86400000).toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'}), count: 45 },
    { date: new Date(Date.now() - 4*86400000).toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'}), count: 38 },
    { date: new Date(Date.now() - 3*86400000).toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'}), count: 42 },
    { date: new Date(Date.now() - 2*86400000).toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'}), count: 50 },
    { date: new Date(Date.now() - 86400000).toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'}), count: 48 },
    { date: new Date().toLocaleDateString('zh-CN', {month: 'numeric', day: 'numeric'}), count: 50 }
  ]
  
  // 备用的任务完成率数据
  taskCompletionData.value = [
    { value: 75, name: '已完成' },
    { value: 25, name: '待处理' }
  ]
  
  // 初始化图表
  initVisitorsChart()
  initTaskCompletionChart()
}

// 窗口大小改变时重新渲染图表
const handleResize = () => {
  visitorsChart?.resize()
  taskCompletionChart?.resize()
}

// 组件挂载时初始化
onMounted(() => {
  // 从后端获取数据
  fetchDashboardData()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载时清理
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  visitorsChart?.dispose()
  taskCompletionChart?.dispose()
})
</script>

<style scoped>
/* 确保组件内所有元素都有过渡效果 */
* {
  transition-property: color, background-color, border-color, text-decoration-color, fill, stroke;
  transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
  transition-duration: 300ms;
}

.dashboard-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.dark .loading-overlay {
  background-color: rgba(0, 0, 0, 0.8);
}

.loading-content {
  text-align: center;
}

.loading-text {
  margin-top: 12px;
  font-size: 16px;
  color: var(--light-text-primary);
}

.dark .loading-text {
  color: var(--dark-text-primary);
}

.blue .loading-overlay {
  background-color: rgba(30, 41, 59, 0.8);
}

.blue .loading-text {
  color: var(--blue-text-primary);
}

.dashboard-header {
  margin-bottom: 24px;
}

/* 统计卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.stat-card {
  height: 120px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
  height: 100%;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  margin-top: 4px;
}

/* 图表容器 */
.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.chart-card {
  height: 350px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-content {
  height: calc(100% - 50px);
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 最近任务 */
.recent-tasks {
  margin-bottom: 24px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .charts-container {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: 1fr 1fr;
  }
  
  .dashboard-header h2 {
    font-size: 20px;
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
  }
  
  .chart-card {
    height: 250px;
  }
}

/* 覆盖Element Plus样式以支持主题切换 */
:deep(.el-card) {
  background-color: var(--bg-secondary-color) !important;
  border-color: var(--border-color) !important;
}

:deep(.el-card__header) {
  background-color: var(--bg-secondary-color) !important;
  border-bottom-color: var(--border-color) !important;
}

:deep(.el-table th) {
  background-color: var(--bg-secondary-color) !important;
  color: var(--text-primary) !important;
  border-color: var(--border-color) !important;
}

:deep(.el-table td) {
  background-color: var(--bg-secondary-color) !important;
  color: var(--text-primary) !important;
  border-color: var(--border-color) !important;
}

:deep(.el-table__empty-text) {
  color: var(--text-secondary) !important;
}

:deep(.el-button--primary) {
  background-color: var(--accent-color) !important;
  border-color: var(--accent-color) !important;
}

:deep(.el-button--primary:hover) {
  background-color: var(--accent-color-hover) !important;
  border-color: var(--accent-color-hover) !important;
}
</style>